package com.blb.shiro;

import com.blb.entity.User;
import com.blb.service.IUserService;
import com.blb.service.impl.UserServiceImpl;
import com.blb.utils.ShiroUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private IUserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        User user = (User) principals.getPrimaryPrincipal();
        System.out.println("授权开始"+user.getUserAccount());
        //角色列表
        Set<String> roles = userService.getRoles(user.getUserAccount());
        Set<String> permision =userService.getPermision(roles);

        System.out.println(roles);
        System.out.println(permision);

        info.setRoles(roles);
        info.setStringPermissions(permision);
        return info;
    }
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String account = (String) token.getPrincipal();
        System.out.println("开始认证"+account);
        User user = userService.login(account);
        System.out.println("-"+ user);
        if ( user==null) {
            throw new UnknownAccountException("用户名不存在");
        }
        ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getUserPassword(),credentialsSalt,getName());
        return info;
    }
}